#coding = 'utf-8'
"""
The MIT License (MIT)
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/fontmaker-client-gui
"""

import os, sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFontComboBox, QFileDialog, QMessageBox
from PyQt5 import QtCore
import main_window_ui


class GUI(object):
	CLIENT_EXE = 'FontMaker_Cli.exe'

	def __init__(self):
		self.__app = QApplication(sys.argv)
		self.__window = QMainWindow()
		self.__ui = main_window_ui.Ui_main_window()
		self.__ui.setupUi(self.__window)

		self.__ctl_combo_fontface = self.__ui.combo_fontface
		self.__ctl_combo_fontsize = self.__ui.combo_fontsize
		self.__ctl_radio_byteorder_lsb = self.__ui.radio_byteorder_lsb
		self.__ctl_radio_byteorder_msb = self.__ui.radio_byteorder_msb
		self.__ctl_radio_scanmode_horizontal = self.__ui.radio_scanmode_horizontal
		self.__ctl_radio_scanmode_vertical = self.__ui.radio_scanmode_vertical
		self.__ctl_check_customized_file = self.__ui.check_customized_file
		self.__ctl_spinbox_offset_x = self.__ui.spinbox_offset_x
		self.__ctl_spinbox_offset_y = self.__ui.spinbox_offset_y
		self.__ctl_button_generate = self.__ui.button_generate
		self.__ctl_button_bold = self.__ui.button_bold
		self.__ctl_button_italic = self.__ui.button_bold
		self.__ctl_button_save_file_dialog = self.__ui.button_save_file_dialog
		self.__ctl_button_load_file_dialog = self.__ui.button_load_file_dialog
		self.__ctl_text_output_file = self.__ui.text_output_file
		self.__ctl_text_input_file = self.__ui.text_input_file

		self.__check_cli_exists()

		# 隐藏标题栏最大化按钮
		self.__window.setWindowFlag(QtCore.Qt.WindowType.WindowMaximizeButtonHint, False)

		# 固定窗体大小，禁止调整
		self.__window.setFixedSize(self.__window.width(), self.__window.height())

		self.__load_fontface()
		self.__load_fontsize()

		# 绑定按钮和下拉列表事件
		self.__ctl_button_save_file_dialog.clicked.connect(lambda:self.__event_save_file_dialog())
		self.__ctl_button_load_file_dialog.clicked.connect(lambda:self.__event_load_file_dialog())
		self.__ctl_button_generate.clicked.connect(lambda:self.__event_save_font_file())
		self.__ctl_combo_fontsize.currentTextChanged.connect(lambda:self.__event_fontsize_changed())
		self.__ctl_check_customized_file.clicked.connect(lambda:self.__event_check_customized())
		self.__ctl_radio_scanmode_horizontal.clicked.connect(lambda:self.__event_radio_scanmode_horizontal())
		self.__ctl_radio_scanmode_vertical.clicked.connect(lambda:self.__event_radio_scanmode_vertical())

	def start(self):
		self.__window.show()
		sys.exit(self.__app.exec())

	def __check_cli_exists(self):
		'''
		检查 FontMaker_Cli.exe 是否存在
		'''
		if not os.path.exists(GUI.CLIENT_EXE):
			QMessageBox().critical(self.__window, '错误', '未找到 FontMaker_Cli.exe，终止运行')
			sys.exit()

	def __load_fontface(self):
		'''
		读取系统字体名称并添加到下拉列表
		'''
		font_list = [QFontComboBox().itemText(i) for i in range(QFontComboBox().count())]

		for font in font_list:
			self.__ctl_combo_fontface.addItem(font)

		index = self.__ctl_combo_fontface.findText('幼圆')
		if index >= 0:
			self.__ctl_combo_fontface.setCurrentIndex(index)

	def __load_fontsize(self):
		'''
		生成备选字体大小添加到下拉列表
		'''
		for size in range(12, 38, 2):
			self.__ctl_combo_fontsize.addItem(str(size))


	def __event_save_file_dialog(self):
		'''
		设置输出文件保存路径和名称
		'''
		file_name = QFileDialog.getSaveFileName(None, "Save Font File...", '.')

		if file_name[0]:
			self.__ctl_text_output_file.setText(file_name[0])

	def __event_load_file_dialog(self):
		'''
		设置输入文件保存路径和名称
		'''
		file_name = QFileDialog.getOpenFileName(None, "Load Text File...", '.')

		if file_name[0]:
			self.__ctl_text_input_file.setText(file_name[0])

	def __event_check_customized(self):
		'''
		启用/禁用 文本文件选择按钮
		'''
		checked = self.__ctl_check_customized_file.isChecked()

		self.__ctl_text_input_file.setEnabled(checked)
		self.__ctl_button_load_file_dialog.setEnabled(checked)

	def __event_radio_scanmode_horizontal(self):
		self.__ctl_radio_byteorder_msb.setEnabled(True)

	def __event_radio_scanmode_vertical(self):
		self.__ctl_radio_byteorder_msb.setEnabled(False)
		self.__ctl_radio_byteorder_lsb.setChecked(True)

	def __event_fontsize_changed(self):
		'''
		检查字体大小下拉列表输入的值是否合法
		'''
		if not str.isdigit(self.__ctl_combo_fontsize.currentText()):
			self.__ctl_combo_fontsize.setCurrentText('')

	def __event_save_font_file(self):
		'''
		生成字库文件
		'''
		argv = []
		argv.append('-f')
		argv.append(self.__ctl_combo_fontface.currentText())
		argv.append('-s')
		argv.append(self.__ctl_combo_fontsize.currentText())
		argv.append('-b' if self.__ctl_button_bold.isChecked() else '-n')

		if self.__ctl_button_italic.isChecked():
			argv.append('-i')

		if self.__ctl_check_customized_file.isChecked() and\
			self.__ctl_text_input_file.text():
			argv.append('--input')
			argv.append(self.__ctl_text_input_file.text())

		argv.append('-x')
		argv.append(self.__ctl_spinbox_offset_x.text())
		argv.append('-y')
		argv.append(self.__ctl_spinbox_offset_y.text())
		argv.append('-l' if self.__ctl_radio_byteorder_lsb.isChecked() else '-m')
		argv.append('-o')
		argv.append(self.__ctl_text_output_file.text() or 'combined.bin')

		def started():
			pass
		
		def finished():
			QMessageBox().information(self.__window, 'Info', 'Finished')

		runner = QtCore.QProcess()
		runner.setProcessChannelMode(QtCore.QProcess.ProcessChannelMode.MergedChannels)
		runner.setWorkingDirectory('.')
		# runner.started.connect(lambda:started())
		# runner.finished.connect(lambda:finished())
		runner.start(GUI.CLIENT_EXE, argv)

		result = ''
		while True:
			pid = runner.processId()
			if pid == 0: break

			runner.waitForReadyRead()
			output = runner.readAllStandardOutput()
			output = bytearray(output).decode('gbk')

			if output:
				result += output

				# for line in output.split('\r\n')[:-1]:
				# 	print(line)

		QMessageBox().information(self.__window, '结果', result)


if __name__ == '__main__':
	gui = GUI()
	gui.start()
